package com.matto1990.app.madlab.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

import com.matto1990.app.madlab.provider.MadlabContract.EventColumns;
import com.matto1990.app.madlab.provider.MadlabContract.MeetupColumns;

public class MadlabDatabase extends SQLiteOpenHelper {
    private static final String TAG = "Madlab.Database";
    private static final String DATABASE_NAME = "madlab.db";
    
    private static final int DATABASE_VERSION = 8;
    
    interface Tables {
        String EVENTS = "events";
        String MEETUPS = "meetups";
        
        String MEETUPS_EVENT_JOIN = "meetups LEFT OUTER JOIN events ON meetups.meetup_event_id=events.event_id";
    }
    
    public MadlabDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + Tables.EVENTS + "("
                   + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                   + EventColumns.EVENT_ID + " STRING NOT NULL,"
                   + EventColumns.EVENT_TITLE + " STRING NOT NULL,"
                   + EventColumns.EVENT_DESCRIPTION + " TEXT,"
                   + EventColumns.EVENT_INTERESTED + " BOOLEAN,"
                   + " UNIQUE (" + EventColumns.EVENT_ID + ") ON CONFLICT REPLACE)");
        
        db.execSQL("CREATE TABLE " + Tables.MEETUPS + "("
                + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + MeetupColumns.MEETUP_ID + " STRING NOT NULL,"
                + MeetupColumns.EVENT_ID + " STRING,"
                + MeetupColumns.MEETUP_TITLE + " STRING,"
                + MeetupColumns.MEETUP_LOCATION + " STRING,"
                + MeetupColumns.MEETUP_DESCRIPTION + " TEXT,"
                + MeetupColumns.MEETUP_ATTENDING + " BOOLEAN,"
                + MeetupColumns.MEETUP_START_DATETIME + " DATETIME,"
                + MeetupColumns.MEETUP_END_DATETIME + " DATETIME,"
                + " UNIQUE (" + MeetupColumns.MEETUP_ID + ") ON CONFLICT REPLACE)");
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Destroying old data during upgrade");

        db.execSQL("DROP TABLE IF EXISTS " + Tables.EVENTS);
        db.execSQL("DROP TABLE IF EXISTS " + Tables.MEETUPS);
        
        onCreate(db);
    }
    
}
